<template>
  <el-dialog title="订单退款" v-model="openOrder" width="400px" append-to-body :close-on-click-modal="false" @close="cancel">
    <el-form ref="formOrderRef" :model="formOrder" :rules="rulesOrder" label-width="100px">
      <el-form-item label="订单号" prop="orderNo">
        <span>{{ formOrder.orderNo }}</span>
      </el-form-item>
      <el-form-item label="订单金额">
        <span>{{ totalAmount }}元</span>
      </el-form-item>
      <el-form-item label="退款金额" prop="refundAmount">
        <el-input-number :precision="2" :min="0" :max="totalAmount" v-model="formOrder.refundAmount" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="DialogRefund">
import { refundOrder } from "@/api/trade/refund";

const { proxy } = getCurrentInstance();

const formOrder = ref({
  orderNo: null,
  refundAmount: 0
})
const openOrder = ref(false)
const rulesOrder = ref({
  orderNo: [{ required: true, trigger: "blur", message: "请选择要退款的订单" }],
  refundAmount: [{ required: true, trigger: "blur", message: "请输入退款金额" }],
})
const orderNo = ref('')
const totalAmount = ref(-1)
const is_pc = ref(false)// 判断PC端 or 手机端


function open(row) {
  openOrder.value = true;
  formOrder.value.orderNo = row.orderNo
  totalAmount.value = row.totalAmount / 100;
}

// 暴露出去
defineExpose({
  open,
})

function cancel() {
  openOrder.value = false;
  reset();
}

// 表单重置
function reset() {
  openOrder.value = false;
  proxy.resetForm("formOrderRef")
}

function submitForm() {
  if (formOrder.value.refundAmount > totalAmount.value) {
    proxy.$modal.msgError(
      "目前可退款的金额为" +
      totalAmount.value +
      "元，退款金额不得超出可退款金额的氛围"
    );
    return;
  }
  if (formOrder.value.refundAmount == 0) {
    proxy.$modal.msgError("退款金额不能为0")
    return;
  }
  proxy.$refs["formOrderRef"].validate((valid) => {
    if (valid) {
      refundOrder({
        orderNo: formOrder.value.orderNo,
        refundAmount: formOrder.value.refundAmount * 100
      }).then((response) => {
        proxy.$modal.msgSuccess("退款成功");
        cancel();
        if (this.reload) reload();
      });
    }
  });
}
</script>
